package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.AsyncRestOperations;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class TodayBestService {

    private static final ObjectMapper MAPPER =new ObjectMapper() ;
    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;


    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;


    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0") //"1.0.0":mongoDB  "1.0.1":es
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Autowired
    private IMService imService;

    /**
     * 查询今日佳人
     * @return
     */
    public TodayBest queryTodayBest() {
        //查询当前的登录信息,从当前线程里获取user对象
        User user = UserThreadLocal.get();

        //查询今日佳人
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            // 默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
        }

        //补全信息
        UserInfo userInfo = this.userInfoService.queryById(user.getId());
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        return todayBest;
    }


    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam) {
        //查询当前的登录信息
        User user = UserThreadLocal.get();


        PageResult pageResult = new PageResult();
        //查询推荐列表对象
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        pageResult.setCounts(0); //前端不参与计算，仅需要返回字段
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        List<RecommendUser> records = pageInfo.getRecords();

        //如果查询得到推荐对象列表为空,则读取默认的id
        if(CollectionUtils.isEmpty(records)){
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                //设置随机分数为70-99
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));

                records.add(recommendUser);
            }
        }

        //遍历RecommendUser对象 将userid(推荐的用户)添加到到集合中
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        //添加一系列的条件查询用户
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        //因为数据比较少这里的筛选先关掉
        if (StringUtils.isNotEmpty(queryParam.getGender())) { //性别条件
            if (queryParam.getGender().equals("man")) {
                //queryWrapper.eq("sex", 1);
            } else {
                //queryWrapper.eq("sex", 2);
            }
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) { //居住城市
            //queryWrapper.eq("city", queryParam.getCity());
        }

        if (queryParam.getAge() != null) { //年龄
            //queryWrapper.lt("age", queryParam.getAge());
        }

        //从数据库查找符合条件的userINfo对象集合
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        List<TodayBest> todayBests = new ArrayList<>();
        //遍历userInfo对象将将数据封装到todayBest对象中,并存入集合
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

            //设置缘分值(遍历推荐对象列表将得分封装到todayBest对象中)
            for (RecommendUser record : records) {
                if(userInfo.getUserId().longValue() == record.getUserId().longValue()){
                    double score = Math.floor(record.getScore());
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }

            todayBests.add(todayBest);
        }

        //排序集合，按照score倒序排序
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        //将今日佳人列表封装到分页结果对象中
        pageResult.setItems(todayBests);

        return pageResult;
    }


    /**
     * 查询今日佳人详情
     *
     * @param userId 佳人用户id
     * @return 今日佳人对象
     */
    public TodayBest queryTodayBestById(Long userId) {
        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        //根据佳人的用户id查询userInfo对象,  将usrinfo对象的信息封装到今日佳人对象中
        UserInfo userInfo = this.userInfoService.queryById(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        //枚举
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        //调用方法查询缘分值
        double score = this.recommendUserService.queryScore(userId, user.getId());
        if(score == 0){
            //如果返回的缘分值为0,则设置一个默认值
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    /**
     * 查询陌生人问题
     * @param userId 陌生人id
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        //是否有问题对象,有就返回问题对象
        if (null != question) {
            return question.getTxt();
        }
        //否则返回空
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryById(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.ssoUrl + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }


    /**
     * 搜附近的人
     * @param gender 性别
     * @param distance 距离
     * @return NearUserVo 附近用户对象集合
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        // 查询当前用户的位置信息
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        // 根据当前用户的位置信息查询附近的好友
        List<UserLocationVo> userLocationList = this.userLocationApi
                .queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));//需要int类型的距离

        //如果查找为空,则返回一个空集合
        if (CollectionUtils.isEmpty(userLocationList)) {
            return Collections.emptyList();
        }

        //遍历查出来的UserLocationVo集合获取其中的userId,添加到集合中
        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationList) {
            userIds.add(locationVo.getUserId());
        }

        //条件: userId相等    有性别条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.in("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.in("sex", SexEnum.WOMAN);
        }

        //根据拼接好的条件查询符合条件的UserInfo
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<NearUserVo> nearUserVoList = new ArrayList<>();

        //遍历UserLocationVo集合 和UserInfo集合  将用户信息封装到NearUser对象集合中
        for (UserLocationVo locationVo : userLocationList) {

            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                // 排除自己
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();

                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());

                    //将封装好的对象添加到集合中
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }

        //返回附近用户对象集合
        return nearUserVoList;
    }

    /**
     * 喜欢
     * @param likeUserId 喜欢的人id
     * @return Boolean
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        //如果返回的id为空代表保存失败
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        //调用方法看是否为相互喜欢
        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    /**
     * 取消喜欢
     * @param likeUserId
     */
    public void disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        this.userLikeApi.deleteUserLike(user.getId(),likeUserId);
    }

    /**
     * 探花
     * @return 今日最佳对象集合
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        //定义每页数量为50
        int count = 50;
        //调用方法获取五十个推荐用户
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);
        //如果返回的records值为空,则使用默认推荐列表
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        //要展示十个推荐用户  以防查的用户不到十个所以取其中最少的
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecords = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机选出推荐的好友
            createRecommendUser(newRecords,records);
        }

        //遍历推荐者对象集合将userId存入集合中
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        //查找所有的userInfo对象
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        //遍历userInfo集合 将信息封装到今日最佳对象
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    /**
     * 递归随机生成推荐好友,保证不重复
     * @param newRecords 新的集合
     * @param records 原来的集合里的数据
     */
    private void createRecommendUser(List<RecommendUser> newRecords, List<RecommendUser> records) {
        //通过索引获取推荐用户
        RecommendUser recommendUser=records.get(RandomUtils.nextInt(0,records.size()));
        //新的推荐用户集合中不包含则添加到集合中
        if (!newRecords.contains(recommendUser)){
            newRecords.add(recommendUser);
        }else{
            //否则开始递归
            createRecommendUser(newRecords,records);
        }
    }
}

